package com.fausto.learnimprint.core.controller.impl

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.fausto.learnimprint.core.model.dto.CommonResult
import com.fausto.learnimprint.core.service.IMessageService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*

/**
 *
 *
 * 前端控制器
 *
 *
 * @author fausto
 * @since 2022-03-28
 */
@Api(tags = ["留言API"], basePath = "/messages")
@RestController
@RequestMapping("/messages")
class MessageController : com.fausto.learnimprint.core.controller.MessageModule {

    @Autowired
    lateinit var messageService: IMessageService


    /**
     *      网站用户留言
     */
    @ApiOperation("新增留言")
    @PostMapping
    override fun saveMessage(
        @ApiParam(value = "留言内容", example = "留言内容测试")
        @RequestParam messageBody: String
    ): CommonResult<Any> {
        return if (messageBody.isBlank()) {
            CommonResult.fail("参数错误")
        } else try {
            if (messageService.saveMessage(messageBody)) {
                CommonResult.ok("留言成功")
            } else {
                CommonResult.fail("留言失败,无法插入至数据库")
            }
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *      管理员删除留言
     */
    @ApiOperation("管理员删除留言")
    @PreAuthorize("hasAuthority('ADMIN')")
    @DeleteMapping("/{messageId}")
    override fun deleteMessage(
        @ApiParam(value = "留言ID", example = "1")
        @PathVariable messageId: Int
    ): CommonResult<Any> {
        return if (messageId < 1) {
            CommonResult.fail("参数错误")
        } else try {
            messageService.removeById(messageId)
            CommonResult.ok("删除留言成功")
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *      分页查询留言
     */
    @ApiOperation("分页查询留言")
    @GetMapping("/{page}/{showCount}")
    override fun getMessages(
        @ApiParam(value = "页面序号数", example = "1")
        @PathVariable page: Int,
        @ApiParam(value = "展示记录数", example = "5")
        @PathVariable showCount: Int
    ): CommonResult<Any> {
        return if (page < 1 || showCount < 1) {
            CommonResult.fail("参数错误")
        } else try {
            val messages =
                messageService.page(Page(page.toLong(), showCount.toLong())).records
            CommonResult.ok("查询留言成功", data = messages)
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }
}
